package com.xianrenit.xianrenpuzi.manager.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import cn.hutool.core.util.IdUtil;
import com.xianrenit.xianrenpuzi.manager.service.CodeImgService;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class CodeImgServiceImpl implements CodeImgService {
    @Resource
    StringRedisTemplate stringRedisTemplate;
    @Override
    public Map<String, String> generateCodeImg() {
        //生成验证码
        CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
        String code = captcha.getCode();
        //1、缓存到redis中：code
        String key = IdUtil.getSnowflake(1, 1).nextIdStr();
        stringRedisTemplate.opsForValue().set("sys:user:code:"+key , code , 10 , TimeUnit.MINUTES);
        //2、响应给前端：codeImg的base64字符串
        String codeImg = captcha.getImageBase64();
        Map<String, String> map = new HashMap<>();
        map.put("codeKey" ,key);
        map.put("codeImg" ,"data:image/png;base64,"+codeImg);
        return map;
    }
}
